package T7_26.Maptest;

import com.alibaba.fastjson.JSON;

import java.io.FileWriter;

public class Write_json {
    public static void write(Object data,String part) throws Exception {
        //处理数据(格式化)
        //创建数组用于存放单个字符以用于判断在该位置是否要加入\n
        char[] endchar = JSON.toJSONString(data).toCharArray();

        StringBuilder endstring = new StringBuilder();

        for(int i=0;i < endchar.length;i++){
            endstring.append(endchar[i]);
            switch (endchar[i]) {
                case '{':
                case '[':
                    endstring.append("\n");
                    break;
                case '}':
                case ']':
                    endstring.insert(endstring.length()-1,"\n");
                    //先删除现在的"}",再加上\n,再加回来"}"(方法已废弃)
                    //endstring.deleteCharAt(endstring.length()-1);
                    //endstring.append("\n");
                    //endstring.append(endchar[i]);
                    break;
                case ',':
                    endstring.append("\n");
                    break;
                default:break;
            }
        }

        //写入格式化后的数据
        FileWriter fileWriter = new FileWriter(part);

        fileWriter.write(String.valueOf(endstring));

        fileWriter.close();

        System.out.println("已写入");
    }
}
